﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using Landscape.Business.FNH;
using Entities = Landscape.Business.Entities;
using Activities = Landscape.Business.FNH.Activities;
using Landscape.Business;
using Landscape.Business.Interface.LDAP;
using NHibernate;
using Telerik.Web.UI;

namespace Landscape.WebApp.WCFServices
{
    [ServiceContract(Namespace = "Landscape")]
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AdministrativeActions
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";

        /// <summary>
        /// Return all the internal system modules.
        /// </summary>
        /// <returns>List of SystemModule</returns>
        [OperationContract]
        public List<SystemModule> GetAllInternalSystemModules()
        {
            List<SystemModule> modules = new List<SystemModule>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetAllInternalSystemModules())
                {
                    modules.Add(new SystemModule(item));
                }
            }

            return modules;
        }

        /// <summary>
        /// Return all the internal system modules by parent id
        /// </summary>
        /// <returns>List of SystemModule</returns>
        [OperationContract]
        public List<SystemModule> GetAllInternalSystemModulesByParentID(Guid? pParentID)
        {
            List<SystemModule> modules = new List<SystemModule>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetAllInternalSystemModules())
                {
                    if (item.ParentModule == pParentID)
                        modules.Add(new SystemModule(item));
                }
            }

            return modules;
        }

        /// <summary>
        /// Return all the external system modules.
        /// </summary>
        /// <returns>List of SystemModule</returns>
        [OperationContract]
        public List<SystemModule> GetAllExternalSystemModules()
        {
            List<SystemModule> modules = new List<SystemModule>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetAllExternalSystemModules())
                {
                    modules.Add(new SystemModule(item));
                }
            }

            return modules;
        }

        [OperationContract]
        public Guid? SaveRole(Role pRole)
        {
            Guid? roleID = null;
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    try
                    {
                        var roleBizObject = pRole.ToBusinessObject(nhSession);

                        Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                        roleID = adminActs.SaveRole(roleBizObject);

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        //Do Sometime
                        trans.Rollback();
                    }
                }
            }

            return roleID;
        }

        [OperationContract]
        public List<Role> GetRoles()
        {
            List<Role> roles = new List<Role>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetAllRoles())
                {
                    roles.Add(new Role(item));
                }
            }

            return roles;
        }

        [OperationContract]
        public int GetRolesCount()
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return adminActivities.GetRoleCount();
            }
        }

        [OperationContract]
        public List<Role> GetRolesByPage(int pPageNo, int pPageSize)
        {
            List<Role> roles = new List<Role>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetAllRoles(pPageNo, pPageSize))
                {
                    roles.Add(new Role(item));
                }
            }

            return roles;
        }

        [OperationContract]
        public Role GetRoleByID(Guid pRoleID)
        {
            Activities.AdminActivities adminActs = new Activities.AdminActivities();
            return new Role(adminActs.GetRoleByID(pRoleID));
        }

        [OperationContract]
        public void DeleteRole(Guid pRoleID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    try
                    {
                        Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                        var roleBizObject = adminActs.GetRoleByID(pRoleID);
                        //roleBizObject.IsDeleted = true;

                        adminActs.DeleteRole(roleBizObject);
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        //Do Sometime
                        trans.Rollback();
                    }
                }
            }
        }

        [OperationContract]
        public bool CheckDuplicateRole(string pRoleName)
        {
            Activities.AdminActivities adminActs = new Activities.AdminActivities();
            return adminActs.CheckDuplicateRole(pRoleName);
        }

        [OperationContract]
        public Guid? SaveUser(UserMaster pUserMaster)
        {
            Guid? userID = null;
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    try
                    {
                        var userBizObject = pUserMaster.ToBusinessObject(nhSession);

                        if (userBizObject != null)
                        {
                            Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                            userID = adminActs.SaveUser(userBizObject);

                            trans.Commit();
                        }
                        else
                        {
                            trans.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        //Do Sometime
                        trans.Rollback();
                    }
                }
            }

            return userID;
        }

        [OperationContract]
        public void DeleteUser(Guid pUserID, Guid pCurrentUserID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                    var userObject = adminActs.GetUserMasterByID(pUserID);
                    userObject.IsDeleted = true;
                    userObject.UpdatedBy = pCurrentUserID;
                    userObject.UpdatedDate = DateTime.Now;

                    adminActs.SaveUser(userObject);

                    trans.Commit();
                }
            }
        }

        /*public void UpdateUserRoles(Guid pUserID, string pRoleIDs)
        {
            if (pRoleIDs != null && !pRoleIDs.Trim().Equals(string.Empty))
            {
                using (var nhSession = NHSessionManager.GetManager().GetSession())
                {
                    using (var trans = nhSession.BeginTransaction())
                    {
                        try
                        {
                            Activities.AdminActivities adminActs = new Activities.AdminActivities();
                            var user = adminActs.GetUserMasterByID(pUserID);

                            if (user != null)
                            {
                                if (user.Roles != null)
                                {
                                    while (user.Roles.Count > 0)
                                        user.Roles.RemoveAt(0);
                                }
                                else
                                {
                                    user.Roles = new List<Entities.Role>();
                                }

                                foreach (var r in pRoleIDs.Split(','))
                                {
                                    if (r.Trim() != string.Empty)
                                    {
                                        user.Roles.Add(adminActs.GetRoleByID(Guid.Parse(r)));
                                    }
                                }

                                nhSession.SaveOrUpdate(user);
                                trans.Commit();
                            }
                            else
                            {
                                trans.Dispose();
                            }
                        }
                        catch (Exception ex)
                        {
                            //Do Sometime
                            trans.Rollback();
                        }
                    }
                }
            }
        }*/

        [OperationContract]
        public List<ResourceMap> UpdateUserResources(Guid pUserID, Guid pRoleID, List<Guid> pDeptIDs, List<Guid> pVesselIDs, string pGroupID)
        {
            List<ResourceMap> resources = new List<ResourceMap>();

            if (pGroupID.Trim() == string.Empty)
                pGroupID = DateTime.Now.ToString("yyyyMMddHHmmss");

            if (pRoleID == null || pRoleID == Guid.Empty)
                throw new Exception("There is no role specified. Select the role to proceed.");

            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                    var user = adminActs.GetUserMasterByID(pUserID);
                    bool hasNewData = false;

                    int totalRows = (pDeptIDs != null && pDeptIDs.Count > 0 ? pDeptIDs.Count : 1) * (pVesselIDs != null && pVesselIDs.Count > 0 ? pVesselIDs.Count : 1) * 1;

                    while (user.Resources.Where(exp => exp.GroupId == pGroupID).Count() > 0)
                    {
                        user.Resources.Remove(user.Resources.Where(exp => exp.GroupId == pGroupID).Take(1).Single());
                    }

                    int deptIdx = 0;
                    int vslIdx = 0;
                    for (var idx = 0; idx < totalRows; idx++)
                    {
                        var res =new Entities.SystemResourceMap()
                        {
                            Role = adminActs.GetRoleByID(pRoleID),                            
                            User = user,
                            GroupId = pGroupID
                        };

                        if (pDeptIDs.Count > 0)
                        {   
                           res.Department = adminActs.GetDepartmentByID(pDeptIDs[deptIdx]);
                        }

                        if(pVesselIDs.Count>0)
                        {
                            res.Vessel = adminActs.GetVesselByCode(pVesselIDs[vslIdx]);
                        }

                        user.Resources.Add(res);
                        hasNewData = true;

                        if (deptIdx == (pDeptIDs.Count - 1))
                            deptIdx = 0;
                        else
                            deptIdx++;

                        if (vslIdx == (pVesselIDs.Count - 1))
                            vslIdx = 0;
                        else
                            vslIdx++;
                    }  

                    if (hasNewData)
                    {
                        nhSession.SaveOrUpdate(user);
                        trans.Commit();
                        user = adminActs.GetUserMasterByID(pUserID);
                        foreach (var item in user.Resources)
                        {
                            resources.Add(new ResourceMap()
                            {
                                ID = item.ID,
                                DepartmentCode = (item.Department != null ? item.Department.ID : Guid.Empty),
                                RoleCode = (item.Role != null ? item.Role.ID : Guid.Empty),
                                UserCode = item.User.ID,
                                VesselCode = (item.Vessel != null ? item.Vessel.ID : Guid.Empty),                                
                            });
                        }
                    }
                }
            }

            return resources;
        }

        [OperationContract]
        public List<ResourceMap> GetUserResources(Guid pUserID, int pPageNo, int pPageSize)
        {
            List<ResourceMap> resources = new List<ResourceMap>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                var user = adminActs.GetUserMasterByID(pUserID);

                foreach (var item in (pPageSize != -1 ? user.Resources.Skip(pPageNo * pPageSize).Take(pPageSize) : user.Resources))
                {
                    resources.Add(new ResourceMap(item));
                }
            }
            return resources;      
        }

        [OperationContract]
        public List<ResourceMap> GetUserResourcesByRole(Guid pUserID, Guid pRoleID)
        {
            List<ResourceMap> resources = new List<ResourceMap>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                var user = adminActs.GetUserMasterByID(pUserID);

                foreach (var item in user.Resources.Where(exp=>exp.Role != null && exp.Role.ID == pRoleID))
                {
                    resources.Add(new ResourceMap(item));
                }
            }
            return resources; 
        }

        [OperationContract]
        public List<ResourceMap> GetUserResourcesByGroup(Guid pUserID, string pGroupID)
        {
            List<ResourceMap> resources = new List<ResourceMap>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                var user = adminActs.GetUserMasterByID(pUserID);

                foreach (var item in user.Resources.Where(exp => exp.GroupId != null && exp.GroupId == pGroupID))
                {
                    resources.Add(new ResourceMap(item));
                }
            }
            return resources; 
        }

        [OperationContract]
        public void DeleteResourceGroup(Guid pUserID, string pGroupID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                    var user = adminActs.GetUserMasterByID(pUserID);

                    while (user.Resources.Where(exp => exp.GroupId == pGroupID).Count() > 0)
                    {
                        var resItem = user.Resources.Where(exp => exp.GroupId == pGroupID).Take(1).Single();
                        resItem.Department = null;
                        resItem.Role = null;
                        resItem.Vessel = null;
                        resItem.User = null;

                        user.Resources.Remove(resItem);
                    }

                    nhSession.SaveOrUpdate(user);
                    trans.Commit();
                }
            }
        }

        [OperationContract]
        public int GetUserResourceCount(Guid pUserID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                var user = adminActs.GetUserMasterByID(pUserID);

                return user.Resources.Count;
            }
        }

        [OperationContract]
        public UserMaster GetAdUserDetails(string pLoginCode)
        {
            UserMaster um = new UserMaster();

            ActiveDirectoryManager adMan = new ActiveDirectoryManager();
            var uDet = adMan.GetUserByLoginName(pLoginCode.Trim());

            um.FirstName = uDet.FirstName;
            um.LastName = uDet.LastName;
            um.IsTpUser = true;
            um.EMail = uDet.EMail;            

            return um;
        }

        [OperationContract]
        public bool CheckForDuplicateLogin(string pLoginCode)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities();
                if (adminActs.GetUserMasterByCredentials(pLoginCode, false) != null)
                {
                    return true;
                }
                return false;
            }
        }

        [OperationContract]
        public List<UserMaster> GetUsersByPage(int pPageNo, int pPageSize)
        {
            List<UserMaster> userList = new List<UserMaster>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetAllUsers(pPageNo, pPageSize))
                {
                    userList.Add(new UserMaster(item));
                }
            }

            return userList;
        }

        [OperationContract]
        public int GetUsersCount()
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return adminActivities.GetUsersCount();
            }
        }

        [OperationContract]
        public UserMaster GetUserByID(Guid pUserID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                return new UserMaster(adminActs.GetUserMasterByID(pUserID));
            }
        }

        [OperationContract]
        public List<Role> GetUserRoles(Guid pUserID, int pPageNo, int pPageSize)
        {
            List<Role> roles = new List<Role>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetUserRoles(pUserID, pPageNo, pPageSize))
                {
                    roles.Add(new Role(item));
                }
            }
            return roles;
        }

        [OperationContract]
        public int GetUserRoleCount(Guid pUserID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return adminActivities.GetUserRoleCount(pUserID);
            }
        }

        /*[OperationContract]
        public List<Vessel> GetUserVessels(Guid pUserID)
        {
            List<Vessel> userVessels = new List<Vessel>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetUserVessels(pUserID))
                {
                    if (item != null)
                        userVessels.Add(new Vessel(item));
                }
            }
            return userVessels;
        }*/

        [OperationContract]
        public bool IsRoleAssigned(Guid pUserID, Guid pRoleID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                var user = adminActs.GetUserMasterByID(pUserID);
                if (!user.IsSystemAdmin)
                {
                    /*if (user.Roles != null && user.Roles.Count > 0)
                    {
                        return user.Roles.Where(Exp => Exp.ID == pRoleID).Count() > 0;
                    }
                    else
                    {
                        return false;
                    }*/
                    if (user.Resources != null && user.Resources.Count > 0)
                    {
                        return user.Resources.Where(Exp => Exp.Role.ID == pRoleID).Count() > 0;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
        }

        [OperationContract]
        public Guid? SaveItem(MachineType pItem)
        {
            Guid itemID = Guid.Empty;
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    try
                    {
                        var itemBizObject = pItem.ToBusinessObject(nhSession);

                        if (itemBizObject != null)
                        {
                            Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                            itemID = adminActs.SaveItem(itemBizObject);

                            trans.Commit();
                        }
                        else
                        {
                            trans.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        //Do Sometime
                        trans.Rollback();
                        throw ex;
                    }
                }
            }

            return itemID;
        }

        [OperationContract]
        public List<MachineType> GetItemsByType(string pItemType, int pPageNo, int pPageSize)
        {
            List<MachineType> items = new List<MachineType>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetItemsByType((MachineCategory)Enum.Parse(typeof(MachineCategory), pItemType), pPageNo, pPageSize))
                {
                    items.Add(new MachineType(item));
                }
            }
            return items;
        }

        [OperationContract]
        public List<MachineType> GetItemsBy(string pName, string pItemType, int pPageNo, int pPageSize)
        {
            List<MachineType> items = new List<MachineType>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetItemsBy(pName, pItemType, pPageNo, pPageSize))
                {
                    items.Add(new MachineType(item));
                }
            }
            return items;
        }

        [OperationContract]
        public int GetItemsCountBy(string pName, string pItemType)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return adminActivities.GetItemsCountBy(pName, pItemType);
            }
        }

        [OperationContract]
        public List<MachineType> GetItemsByParent(Guid pParentID, int pPageNo, int pPageSize)
        {
            List<MachineType> items = new List<MachineType>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);                
                foreach (var item in adminActivities.GetConstituentsByParentID(pParentID, pPageNo, pPageSize))
                {
                    items.Add(new MachineType(item));
                }
            }
            return items;
        }

        [OperationContract]
        public int GetItemsCountByParent(Guid pParentID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return adminActivities.GetConstituentsCountByParentID(pParentID);
            }
        }

        [OperationContract]
        public MachineType GetItemByID(Guid pID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return new MachineType(adminActivities.GetItemByID(pID));
            }
        }

        [OperationContract]
        public List<MachineType> GetConstituentsByParentID(Guid pParentID, int pPageNo, int pPageSize)
        {
            List<MachineType> items = new List<MachineType>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetConstituentsByParentID(pParentID, pPageNo, pPageSize))
                {
                    items.Add(new MachineType(item));
                }
            }
            return items;
        }

        [OperationContract]
        public int GetConstituentsCountByParentID(Guid pParentID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return adminActivities.GetConstituentsCountByParentID(pParentID);
            }
        }

        [OperationContract]
        public void DeleteItems(string pItemIDList, Guid pUserID)
        {
            if (pItemIDList.Trim() != string.Empty && pItemIDList.Trim().Split(';').Count() > 1)
            {
                using (var nhSession = NHSessionManager.GetManager().GetSession())
                {
                    using (var trans = nhSession.BeginTransaction())
                    {
                        Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                        adminActivities.DeleteItems(pItemIDList.Trim().Split(';'), pUserID);

                        trans.Commit();
                    }
                }
            }
        }

        [OperationContract]
        public Guid? SaveTemplate(Template pTemplate)
        {
            Guid? itemID = null;
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    try
                    {
                        var templateBizObject = pTemplate.ToBusinessObject(nhSession);

                        if (templateBizObject != null)
                        {
                            Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                            itemID = adminActs.SaveTemplate(templateBizObject);

                            trans.Commit();
                        }
                        else
                        {
                            trans.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        //Do Sometime
                        trans.Rollback();
                        throw ex;
                    }
                }
            }

            return itemID;
        }

        [OperationContract]
        public List<Template> GetTemplatesByName(string pName, int pPageNo, int pPageSize)
        {
            List<Template> items = new List<Template>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetTemplatesByName(pName, pPageNo, pPageSize))
                {
                    items.Add(new Template(item));
                }
            }
            return items;
        }

        [OperationContract]
        public int GetTemplateCountByName(string pName)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return adminActivities.GetTemplateCountByName(pName);
            }
        }

        [OperationContract]
        public Template GetTemplateByID(Guid pID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return new Template(adminActivities.GetTemplateByID(pID));
            }
        }

        [OperationContract]
        public void AddTemplateMachinery(TemplateMachinery pTemplateMachinery, Guid pTemplateID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    try
                    {
                        var templateBizObject = pTemplateMachinery.ToBusinessObject(nhSession);

                        if (templateBizObject != null)
                        {
                            Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                            var template = adminActs.GetTemplateByID(pTemplateID);
                            if (template.MachineItems == null)
                                template.MachineItems = new List<Entities.TemplateMachinery>();
                            template.MachineItems.Add(pTemplateMachinery.ToBusinessObject(nhSession));
                            adminActs.SaveEntity<Entities.Template>(template);

                            trans.Commit();
                        }
                        else
                        {
                            trans.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        //Do Sometime
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        [OperationContract]
        public List<TemplateMachinery> GetTemplateMachineryListByParent(Guid pTemplateID, Guid? pParentID)
        {
            List<TemplateMachinery> list = new List<TemplateMachinery>();

            if (!pParentID.HasValue)
                pParentID = Guid.Empty;

            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                var template = adminActs.GetTemplateByID(pTemplateID);
                if (template != null && template.MachineItems != null)
                {
                    if (template.MachineItems.Where(exp => exp.ParentId == pParentID) != null)
                    {
                        foreach (var item in template.MachineItems.Where(exp => exp.ParentId == pParentID))
                        {
                            list.Add(new TemplateMachinery(item));
                        }
                    }
                }
            }

            return list;
        }

        [OperationContract]
        public List<TemplateMachinery> GetTemplateMachineryListByParentEx(Guid pTemplateID, Guid? pParentID, Guid pVesselCode)
        {
            List<TemplateMachinery> list = new List<TemplateMachinery>();

            if (!pParentID.HasValue)
                pParentID = Guid.Empty;

            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                var template = adminActs.GetTemplateByID(pTemplateID);
                if (template != null && template.MachineItems != null)
                {
                    if (template.MachineItems.Where(exp => exp.ParentId == pParentID) != null)
                    {
                        foreach (var item in template.MachineItems.Where(exp => exp.ParentId == pParentID))
                        {
                            var tm = new TemplateMachinery(item);
                            var vslItem = adminActs.CheckItemInVesselItem(pVesselCode, item.MachineItem.ID);
                            tm.AttachedToVessel = (vslItem != Guid.Empty);
                            tm.VesselItemID = vslItem;
                            list.Add(tm);
                        }
                    }
                }
            }

            return list;
        }

        [OperationContract]
        public List<MachineType> GetItemsByParentForTemplate(Guid? pParentID, Guid pTemplateID, int pPageNo, int pPageSize)
        {
            List<MachineType> items = new List<MachineType>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetItemsByParentForTemplate(pParentID, pTemplateID, pPageNo, pPageSize))
                {
                    items.Add(new MachineType(item));
                }
            }
            return items;
        }

        [OperationContract]
        public int GetItemsCountByParentForTemplate(Guid? pParentID, Guid pTemplateID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return adminActivities.GetItemsCountByParentForTemplate(pParentID, pTemplateID);
            }
        }

        [OperationContract]
        public void RemoveTemplateItems(Guid pTemplateID, List<TemplateMachinery> pItems)
        {
            if (pItems != null && pItems.Count > 0)
            {
                /*pItems.Sort(new Comparison<TemplateMachinery>((a, b) => { return 
                    (a.ParentID==null && b.ParentID==null? 0:
                    (a.ParentID==null && b.ParentID!=null)?-1:
                    (a.ParentID!=null && b.ParentID==null)?1:
                    ((a.ParentID!=null && b.ParentID!= null)&& a.ParentID>b.ParentID?1:
                    ((a.ParentID!=null && b.ParentID!= null)&& a.ParentID<b.ParentID?-1:0))); }));*/

                using (var nhSession = NHSessionManager.GetManager().GetSession())
                {
                    using (var trans = nhSession.BeginTransaction())
                    {
                        Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                        adminActivities.RemoveTemplateItems(pTemplateID, pItems.Select(i => i.ID).ToList());

                        trans.Commit();
                    }
                }
            }
        }

        [OperationContract]
        public void DeleteTemplate(Guid pTemplateID, Guid pUserID)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                    var template = adminActs.GetTemplateByID(pTemplateID);
                    template.IsDeleted = true;
                    template.UpdatedBy = pUserID;
                    template.UpdatedDate = DateTime.Now;

                    adminActs.SaveEntity<Entities.Template>(template);

                    trans.Commit();
                }
            }
        }

        [OperationContract]
        public Guid? SaveVessel(Vessel pVessel)
        {
            Guid? vID = null;
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                    vID = adminActs.SaveVessel(pVessel.ToBusinessObject(nhSession));

                    trans.Commit();
                }
            }

            return vID;
        }

        [OperationContract]
        public Vessel GetVesselByCode(Guid pVesselCode)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return new Vessel(adminActivities.GetVesselByCode(pVesselCode));
            }
        }

        [OperationContract]
        public List<Vessel> GetVesselListByName(string pName, int pPageNo, int pPageSize)
        {
            List<Vessel> items = new List<Vessel>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetVesselsByName(pName, pPageNo, pPageSize))
                {
                    items.Add(new Vessel(item));
                }
            }
            return items;
        }

        [OperationContract]
        public List<TemplateMachinery> GetTemplateMachineryByVessel(Guid pVesselCode)
        {
            List<TemplateMachinery> mach = new List<TemplateMachinery>();

            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                var vsl = adminActivities.GetVesselByCode(pVesselCode);
                foreach (var item in vsl.SystemsTemplate.MachineItems)
                {
                    var tm = new TemplateMachinery(item);
                    var vslItemID = adminActivities.CheckItemInVesselItem(pVesselCode, item.MachineItem.ID);
                    tm.AttachedToVessel = (vslItemID != Guid.Empty);
                    tm.VesselItemID = vslItemID;
                    mach.Add(tm);
                }
            }

            return mach;
        }

        [OperationContract]
        public List<Vessel> GetUserVessels(Guid pUserCode)
        {
            List<Vessel> items = new List<Vessel>();
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                var ud = adminActivities.GetUserMasterByID(pUserCode);
                if (ud.Resources != null)
                {
                    if (ud.Resources.Where(exp => exp.Vessel != null).Count() > 0)
                    {
                        foreach (var resource in ud.Resources)
                        {
                            items.Add(new Vessel(resource.Vessel));
                        }
                    }
                    else
                    {
                        foreach (var vsl in adminActivities.GetVesselsByName("", 0, -1))
                        {
                            items.Add(new Vessel(vsl));
                        }
                    }
                }
                else
                {
                    foreach (var vsl in adminActivities.GetVesselsByName("", 0, -1))
                    {
                        items.Add(new Vessel(vsl));
                    }
                }
            }
            return items;
        }

        [OperationContract]
        public SystemCode GetSystemCodeByName(string pName)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return new SystemCode(adminActivities.GetSystemCodeByName(pName));
            }
        }

        [OperationContract]
        public VesselMachine GetVesselItemByCode(Guid pCode)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                return new VesselMachine(adminActivities.GetVesselItemByCode(pCode));
            }
        }

        [OperationContract]
        public void SaveVesselItem(VesselMachine pVesselIte)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    Activities.AdminActivities adminActs = new Activities.AdminActivities(nhSession);
                    adminActs.SaveEntity<Entities.VesselMachine>(pVesselIte.ToBusinessObject(nhSession));
                }
            }
        }

        [OperationContract]
        public RadComboBoxData GetUserList(RadComboBoxContext context)
        {
            RadComboBoxData result = new RadComboBoxData();

            var users = this.GetUsersByPage(0, -1).Where(exp => exp.FirstName.ToLower().StartsWith(context["Text"].ToString().ToLower()) && exp.IsDeleted == false && exp.IsDisabled == false).Select(exp => new { 
                FullName = exp.FirstName + " "+exp.LastName,
                UID = exp.ID
            });

            List<RadComboBoxItemData> items = new List<RadComboBoxItemData>();
            foreach (var user in users)
            {
                RadComboBoxItemData item = new RadComboBoxItemData()
                {
                    Text = user.FullName,
                    Value = user.UID.ToString(),
                    //set the attribute of the item which will be used in the ClientDataBound event                            
                    //Attributes = new Dictionary<string, object> { { "ImageUrl", radControl + ".gif" } }
                };

                items.Add(item);
            }
            result.Items = items.ToArray();

            return result;
        }

        [OperationContract]
        public List<Department> GetUserDepartments(Guid pUserCode)
        {
            List<Department> depts = new List<Department>();

            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(nhSession);
                foreach (var item in adminActivities.GetUserDepartments(pUserCode))
                {
                    depts.Add(new Department(item));
                }
            }

            return depts;
        }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SystemModule
    {
        public SystemModule()
        { this.ID = Guid.Empty; }

        public SystemModule(Entities.SystemModule pBusinessEntity)
        {
            this.ID = pBusinessEntity.ID;
            this.Name = pBusinessEntity.Name;
            this.Description = pBusinessEntity.Description;
            this.Url = pBusinessEntity.Url;
            this.IndexNumber = pBusinessEntity.IndexNumber;
            this.ParentModule = pBusinessEntity.ParentModule;
            this.IsLeaf = pBusinessEntity.IsLeaf;
            this.IsDeleted = pBusinessEntity.IsDeleted;
            this.IsDisabled = pBusinessEntity.IsDisabled;
            this.Location = pBusinessEntity.Location;

            this.Privileges = new List<SystemModulePrivilege>();
            foreach (var item in pBusinessEntity.Privileges)
            {
                this.Privileges.Add(new SystemModulePrivilege(item));
            }
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string Description
        { get; set; }

        [DataMember]
        public string Url
        { get; set; }

        [DataMember]
        public int IndexNumber
        { get; set; }

        [DataMember]
        public Guid? ParentModule
        { get; set; }

        [DataMember]
        public bool IsLeaf
        { get; set; }

        [DataMember]
        public bool IsDisabled
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        [DataMember]
        public string Location
        { get; set; }

        [DataMember]
        public List<SystemModulePrivilege> Privileges
        { get; set; }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SystemModulePrivilege
    {
        public SystemModulePrivilege()
        { this.ID = Guid.Empty; }

        public SystemModulePrivilege(Entities.SystemModulePrivilege pBusinessEntity)
        {
            this.ID = pBusinessEntity.ID;
            this.Name = pBusinessEntity.Name;
            this.Description = pBusinessEntity.Description;
            this.IndexNumber = pBusinessEntity.IndexNumber;
            this.IsDisabled = pBusinessEntity.IsDisabled;
            this.IsDeleted = pBusinessEntity.IsDeleted;
            this.ModuleID = pBusinessEntity.Module.ID;
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string Description
        { get; set; }

        [DataMember]
        public int IndexNumber
        { get; set; }

        [DataMember]
        public bool IsDisabled
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        [DataMember]
        public Guid ModuleID
        { get; set; }

        //[DataMember]
        //public IList<Role> Roles
        //{ get; set; }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Role
    {        
        public Role()
        { this.ID = Guid.Empty; }

        public Role(Entities.Role pBusinessEntity)
        {
            this.ID = pBusinessEntity.ID;
            this.CreatedBy = pBusinessEntity.CreatedBy;
            this.CreatedDate = pBusinessEntity.CreatedDate;
            this.Description = pBusinessEntity.Description;
            this.IsDeleted = pBusinessEntity.IsDeleted;
            this.IsDisabled = pBusinessEntity.IsDisabled;
            this.Name = pBusinessEntity.Name;
            this.UpdatedBy = pBusinessEntity.UpdatedBy;
            this.UpdatedDate = pBusinessEntity.UpdatedDate;

            this.Privileges = new List<Guid>();
            foreach (var item in pBusinessEntity.Privileges)
            {
                this.Privileges.Add(item.ID);
            }
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string Description
        { get; set; }

        [DataMember]
        public bool IsDisabled
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        [DataMember]
        public List<Guid> Privileges
        { get; set; }

        [DataMember]
        public Guid CreatedBy
        { get; set; }

        [DataMember]
        public DateTime CreatedDate
        { get; set; }

        [DataMember]
        public Guid UpdatedBy
        { get; set; }

        [DataMember]
        public DateTime UpdatedDate
        { get; set; }
        
        public Entities.Role ToBusinessObject(NHibernate.ISession pSession)
        {
            Entities.Role bRole = null;
            if (this.ID != Guid.Empty)
            {
                Activities.AdminActivities adminBizActs = new Activities.AdminActivities(pSession);
                if (adminBizActs.HasRoleExists(this.ID))
                {
                    bRole = adminBizActs.GetRoleByID(this.ID);

                    bRole.Description = this.Description;
                    bRole.IsDeleted = this.IsDeleted;
                    bRole.IsDisabled = this.IsDisabled;
                    bRole.Name = this.Name;
                    bRole.UpdatedBy = this.UpdatedBy;
                    bRole.UpdatedDate = DateTime.Now;

                    if (this.Privileges != null)
                    {
                        if (bRole.Privileges == null)
                            bRole.Privileges = new List<Entities.SystemModulePrivilege>();

                        while (bRole.Privileges.Count > 0)
                            bRole.Privileges.RemoveAt(0);
                        
                        foreach (var p in this.Privileges)
                        {                            
                            bRole.Privileges.Add(adminBizActs.GetPrivilegeByID(p));
                        }
                    }
                }
            }
            else
            {
                bRole = new Entities.Role();
                bRole.CreatedBy = this.CreatedBy;
                bRole.CreatedDate = DateTime.Now;
                bRole.Description = this.Description;
                bRole.IsDeleted = false;
                bRole.IsDisabled = false;
                bRole.Name = this.Name;
                bRole.UpdatedBy = this.UpdatedBy;
                bRole.UpdatedDate = DateTime.Now;

                Activities.AdminActivities adminBizActs = new Activities.AdminActivities();
                bRole.Privileges = new List<Entities.SystemModulePrivilege>();
                if (this.Privileges != null)
                {
                    foreach (var p in this.Privileges)
                    {
                        bRole.Privileges.Add(adminBizActs.GetPrivilegeByID(p));
                    }
                }
            }

            return bRole;
        }
    }

    [KnownType(typeof(UserMaster))]
    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]    
    public class UserIdentity : IExtensibleDataObject
    {        
        public UserIdentity()
        { this.ID = Guid.Empty; }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string LoginName
        { get; set; }

        [DataMember]
        public bool IsAdUser
        { get; set; }

        [DataMember]
        public DateTime? LastLoginTime
        { get; set; }

        [DataMember]
        public string IpAddress
        { get; set; }

        public Entities.UserIdentity ToBusinessObject(NHibernate.ISession pSession)
        {
            Entities.UserIdentity uIdntity = null;

            if (this.ID == Guid.Empty)
            {
                uIdntity = new Entities.UserIdentity();
            }
            else
            {
                Activities.AdminActivities adminBizActs = new Activities.AdminActivities(pSession);
                uIdntity = adminBizActs.GetUserIdentityByID(this.ID);
            }

            uIdntity.IsAdUser = this.IsAdUser;
            uIdntity.LoginName = this.LoginName;

            return uIdntity;
        }

        public ExtensionDataObject ExtensionData
        {
            get;
            set;
        }
    }

    [KnownType(typeof(ResourceMap))]
    [KnownType(typeof(Role))]
    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]   
    public class UserMaster : IExtensibleDataObject
    {
        public UserMaster()
        { this.ID = Guid.Empty; }

        public UserMaster(Entities.UserMaster pBusinessObject)
        {
            this.ID = pBusinessObject.ID;
            this.CreatedBy = pBusinessObject.CreatedBy;
            this.CreatedDate = pBusinessObject.CreatedDate;
            this.EMail = pBusinessObject.EMail;
            this.FirstName = pBusinessObject.FirstName;            
            this.IsDeleted = pBusinessObject.IsDeleted;
            this.IsDisabled = pBusinessObject.IsDisabled;
            this.IsSystemAdmin = pBusinessObject.IsSystemAdmin;
            this.LastName = pBusinessObject.LastName;
            this.PhoneNumber = pBusinessObject.PhoneNumber;
            //this.Resources = pBusinessObject.Resources;            
            this.Salutation = pBusinessObject.Salutation;
            this.UpdatedBy = pBusinessObject.UpdatedBy;
            this.UpdatedDate = pBusinessObject.UpdatedDate;

            if (pBusinessObject.Identity != null)
            {
                this.Identity = new UserIdentity()
                {
                    ID = pBusinessObject.Identity.ID,
                    IpAddress = pBusinessObject.Identity.IpAddress,
                    IsAdUser = pBusinessObject.Identity.IsAdUser,
                    LastLoginTime = pBusinessObject.Identity.LastLoginTime,
                    LoginName = pBusinessObject.Identity.LoginName
                };
            }

            /*this.Roles = new List<Role>();
            if (pBusinessObject.Roles != null && pBusinessObject.Roles.Count > 0)
            {
                foreach (var item in pBusinessObject.Roles)
                    this.Roles.Add(new Role(item));
            }*/
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public int StaffCode
        { get; set; }

        [DataMember]
        public string FirstName
        { get; set; }

        [DataMember]
        public string LastName
        { get; set; }

        [DataMember]
        public string Salutation
        { get; set; }

        [DataMember]
        public bool IsTpUser
        { get; set; }

        [DataMember]
        public string EMail
        { get; set; }

        [DataMember]
        public string PhoneNumber
        { get; set; }

        [DataMember]
        public bool IsSystemAdmin
        { get; set; }

        [DataMember]
        public bool IsDisabled
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        [DataMember]
        public Guid CreatedBy
        { get; set; }

        [DataMember]
        public DateTime CreatedDate
        { get; set; }

        [DataMember]
        public Guid UpdatedBy
        { get; set; }

        [DataMember]
        public DateTime UpdatedDate
        { get; set; }

        [DataMember]
        public IList<Role> Roles
        { get; set; }

        [DataMember]
        public IList<ResourceMap> Resources
        { get; set; }

        [DataMember]
        public UserIdentity Identity
        { get; set; }

        [DataMember]
        public string Location
        { get; set; }

        [DataMember]
        public List<Guid> VesselCodes
        { get; set; }

        internal Entities.UserMaster ToBusinessObject(NHibernate.ISession pSession)
        {
            Entities.UserMaster uMaster = null;
            Activities.AdminActivities adminActs = new Activities.AdminActivities(pSession);

            if (this.ID == Guid.Empty)
            {
                uMaster = new Entities.UserMaster();
                uMaster.CreatedBy = this.CreatedBy;
                uMaster.CreatedDate = DateTime.Now;

                uMaster.Identity = this.Identity.ToBusinessObject(pSession);
            }
            else
            {
                uMaster = pSession.Get<Entities.UserMaster>(this.ID);
            }

            uMaster.EMail = this.EMail;
            uMaster.FirstName = this.FirstName;
            uMaster.IsDeleted = false;
            uMaster.IsDisabled = false;
            uMaster.IsSystemAdmin = false;
            uMaster.LastName = this.LastName;
            uMaster.PhoneNumber = this.PhoneNumber;
            uMaster.Salutation = this.Salutation;
            uMaster.UpdatedBy = this.UpdatedBy;
            uMaster.UpdatedDate = DateTime.Now;
            uMaster.Location = (Locations)Enum.Parse(typeof(Locations), this.Location);
                       
            /*uMaster.Vessels.Clear();
            if (this.VesselCodes != null && this.VesselCodes.Count > 0)
            {
                this.VesselCodes.ForEach(act => { uMaster.Vessels.Add(adminActs.GetVesselByCode(act)); });
            }*/

            /*while (uMaster.Resources != null && uMaster.Resources.Count > 0)
                uMaster.Resources.RemoveAt(0);

            if (this.Resources != null)
            {
                foreach (var item in this.Resources)
                {
                    var bizO = item.ToBusinessObject(pSession);
                    bizO.User = uMaster;

                    uMaster.Resources.Add(bizO);
                }
            }*/

            /*while (uMaster.Roles != null && uMaster.Roles.Count > 0)
                uMaster.Roles.RemoveAt(0);

            if (this.Roles != null)
            {                
                foreach (var item in this.Roles)
                {
                    uMaster.Roles.Add(adminActs.GetRoleByID(item.ID));
                }
            } */

            return uMaster;
        }

        internal Entities.UserMaster ToBusinessObject(NHibernate.ISession pSession, Entities.UserMaster pCurrentUser)
        {
            Entities.UserMaster uMaster = pCurrentUser;
            Activities.AdminActivities adminActs = new Activities.AdminActivities(pSession);

            uMaster.EMail = this.EMail;
            uMaster.FirstName = this.FirstName;
            uMaster.IsDeleted = false;
            uMaster.IsDisabled = false;
            uMaster.IsSystemAdmin = false;
            uMaster.LastName = this.LastName;
            uMaster.PhoneNumber = this.PhoneNumber;
            uMaster.Salutation = this.Salutation;
            uMaster.UpdatedBy = this.UpdatedBy;
            uMaster.UpdatedDate = this.UpdatedDate;
            uMaster.Location = (Locations)Enum.Parse(typeof(Locations), this.Location);

            //if (this.VesselCodes != Guid.Empty)
            //    uMaster.Vessel = adminActs.GetVesselByCode(this.VesselCodes);

            /*if (this.VesselCodes != null && this.VesselCodes.Count > 0)
            {
                this.VesselCodes.ForEach(act => { uMaster.Vessels.Add(adminActs.GetVesselByCode(act)); });
            }

            while (uMaster.Resources.Count > 0)
                uMaster.Resources.RemoveAt(0);

            foreach (var item in this.Resources)
            {
                var bizO = item.ToBusinessObject(pSession);
                bizO.User = uMaster;

                uMaster.Resources.Add(bizO);
            }

            while (uMaster.Roles.Count > 0)
                uMaster.Roles.RemoveAt(0);

            foreach (var item in this.Roles)
            {
                uMaster.Roles.Add(item.ToBusinessObject(pSession));
            }*/

            return uMaster;
        }

        public ExtensionDataObject ExtensionData
        {
            get;
            set;
        }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]   
    public class ResourceMap
    {
        public ResourceMap()
        { this.ID = Guid.Empty; }

        public ResourceMap(Entities.SystemResourceMap pBusinessObject)
        {
            this.ID = pBusinessObject.ID;
            this.UserCode = pBusinessObject.User.ID;
            this.DepartmentCode = (pBusinessObject.Department != null ? pBusinessObject.Department.ID : Guid.Empty);
            this.RoleCode = (pBusinessObject.Role != null ? pBusinessObject.Role.ID : Guid.Empty);
            this.VesselCode = (pBusinessObject.Vessel != null ? pBusinessObject.Vessel.ID : Guid.Empty); 

            this.Department = (pBusinessObject.Department != null ? pBusinessObject.Department.Name : "-");
            this.RoleName = (pBusinessObject.Role != null ? pBusinessObject.Role.Name : "-");
            this.VesselName = (pBusinessObject.Vessel != null ? pBusinessObject.Vessel.Name : "-");
            this.GroupID = pBusinessObject.GroupId;
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string GroupID
        { get; set; }

        [DataMember]
        public Guid UserCode
        { get; set; }

        [DataMember]
        public Guid DepartmentCode
        { get; set; }

        [DataMember]
        public string Department
        { get; set; }

        [DataMember]
        public Guid VesselCode
        { get; set; }

        [DataMember]
        public string VesselName
        { get; set; }

        [DataMember]
        public Guid RoleCode
        { get; set; }

        [DataMember]
        public string RoleName
        { get; set; }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]   
    public class Department
    {
        public Department()
        {
            this.ID = Guid.Empty;
        }

        public Department(Entities.Department pBusinessObject)
        {
            if (pBusinessObject != null)
            {
                this.ID = pBusinessObject.ID;
                this.Name = pBusinessObject.Name;
                //this.Description = pBusinessObject.Description;
                this.Location = pBusinessObject.Location.ToString();
                this.IsDeleted = pBusinessObject.IsDeleted;
            }
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string Description
        { get; set; }

        [DataMember]
        public string Location
        { get; set; }
               
        [DataMember]
        public bool IsDeleted
        { get; set; }
    }

    /*[DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UserResource
    {
        public UserResource()
        { this.ID = Guid.Empty; }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public Guid ResourceID
        { get; set; }

        [DataMember]
        public string ResourceKey
        { get; set; }

        internal Entities.UserResource ToBusinessObject(NHibernate.ISession pSession)
        {
            Entities.UserResource uResource = null;

            if (this.ID == Guid.Empty)
            {
                uResource = new Entities.UserResource();

                Activities.AdminActivities adminBizActs = new Activities.AdminActivities(pSession);
                uResource.Resource = adminBizActs.GetSystemResourceByID(this.ResourceID);
                uResource.ResourceKey = this.ResourceKey;
            }

            return uResource;
        }
    }*/

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MachineType
    {
        public MachineType()
        {
            this.ID = Guid.Empty;
            this.Synonyms = new List<string>();
        }

        public MachineType(Entities.MachineType pBusinessEntity)
        {
            this.ID = pBusinessEntity.ID;
            this.Name = pBusinessEntity.Name;
            this.Specifications = pBusinessEntity.Specifications;
            this.Description = pBusinessEntity.Description;
            this.Category = pBusinessEntity.Category.ToString();
            this.IsBusinessCritical = pBusinessEntity.IsBusinessCritical;
            this.IsEnvironmentCritical = pBusinessEntity.IsEnvironmentCritical;
            this.IsSafetyCritical = pBusinessEntity.IsSafetyCritical;
            this.IsDeleted = pBusinessEntity.IsDeleted;
            this.IsDisabled = pBusinessEntity.IsDisabled;
            this.IsMandatory = pBusinessEntity.IsMandatory;

            if (pBusinessEntity.Parent != null)
                this.ParentID = pBusinessEntity.Parent.ID;

            this.CreatedBy = pBusinessEntity.CreatedBy;
            this.CreatedDate = pBusinessEntity.CreatedDate;
            this.UpdatedBy = pBusinessEntity.UpdatedBy;
            this.UpdatedDate = pBusinessEntity.UpdatedDate;
            this.Synonyms = new List<string>();
            if (pBusinessEntity.Synonyms != null && pBusinessEntity.Synonyms.Count > 0)
            {
                foreach (var item in pBusinessEntity.Synonyms)
                {
                    this.Synonyms.Add(item.Name);
                }
            }
        }        

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string Description
        { get; set; }

        [DataMember]
        public string Specifications
        { get; set; }

        [DataMember]
        public List<string> Synonyms
        { get; set; }

        [DataMember]
        public string Category
        { get; set; }

        [DataMember]
        public Guid? ParentID
        { get; set; }

        [DataMember]
        public bool IsBusinessCritical
        { get; set; }

        [DataMember]
        public bool IsEnvironmentCritical
        { get; set; }

        [DataMember]
        public bool IsSafetyCritical
        { get; set; }

        [DataMember]
        public bool IsMandatory
        { get; set; }

        [DataMember]
        public bool IsDisabled
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        [DataMember]
        public Guid CreatedBy
        { get; set; }

        [DataMember]
        public DateTime CreatedDate
        { get; set; }

        [DataMember]
        public Guid UpdatedBy
        { get; set; }

        public DateTime UpdatedDate
        { get; set; }

        public Entities.MachineType ToBusinessObject(NHibernate.ISession pSession)
        {
            Entities.MachineType item = null;

            if (this.ID == Guid.Empty)
            {
                item = new Entities.MachineType();
                item.CreatedBy = this.CreatedBy;
                item.CreatedDate = DateTime.Now;                
            }
            else
            {
                item = pSession.Get<Entities.MachineType>(this.ID);
            }

            if (this.Name != item.Name)
                item.Name = this.Name;

            if (this.Description != item.Description)
                item.Description = this.Description;

            if (this.Specifications != item.Specifications)
                item.Specifications = this.Specifications;

            //if (this.Type != item.C.ToString())
            //    item.Type = (ItemType)Enum.Parse(typeof(ItemType), this.Type);

            item.IsBusinessCritical = this.IsBusinessCritical;
            item.IsEnvironmentCritical = this.IsEnvironmentCritical;
            item.IsSafetyCritical = this.IsSafetyCritical;
            item.IsDeleted = this.IsDeleted;
            item.IsDisabled = this.IsDeleted;
            item.IsMandatory = this.IsMandatory;

            item.UpdatedBy = this.UpdatedBy;
            item.UpdatedDate = DateTime.Now;

            if (this.Synonyms != null)
            {
                while (item.Synonyms.Count > 0)
                {
                    item.Synonyms.RemoveAt(0);
                }

                foreach (var syn in this.Synonyms)
                {
                    if (syn != null && syn.Trim() != string.Empty)
                        item.Synonyms.Add(new Entities.MachineSynonym() { Name = syn });
                }
            }

            if (this.ParentID != null)
            {
                Activities.AdminActivities adminActivities = new Activities.AdminActivities(pSession);
                item.Parent = adminActivities.GetItemByID(this.ParentID.Value);
            }

            return item;
        }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Template
    {
        public Template()
        {
            this.ID = Guid.Empty;
            //MachineItems = new List<TemplateMachinery>();
        }

        public Template(Entities.Template pTemplate)
        {
            this.ID = pTemplate.ID;
            this.Name = pTemplate.Name;
            this.Description = pTemplate.Description;
            this.IsDeleted = pTemplate.IsDeleted;
            this.IsDisabled = pTemplate.IsDisabled;
            this.CreatedBy = pTemplate.CreatedBy;
            this.CreatedDate = pTemplate.CreatedDate;
            this.UpdatedBy = pTemplate.UpdatedBy;
            this.UpdatedDate = pTemplate.UpdatedDate;
            if (pTemplate.MachineItems != null)
            {
                //this.MachineItems = new List<TemplateMachinery>();
                //foreach (var item in pTemplate.MachineItems)
                //{
                //    MachineItems.Add(new TemplateMachinery(item));
                //}
                this.MachineItemCount = pTemplate.MachineItems.Count;
            }
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string Description
        { get; set; }

        [DataMember]
        public int MachineItemCount
        { get; private set; }

        [DataMember]
        public bool IsDisabled
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        [DataMember]
        public Guid CreatedBy
        { get; set; }

        [DataMember]
        public DateTime CreatedDate
        { get; set; }

        [DataMember]
        public Guid UpdatedBy
        { get; set; }

        [DataMember]
        public DateTime UpdatedDate
        { get; set; }

        internal Entities.Template ToBusinessObject(NHibernate.ISession pSession)
        {
            Entities.Template template = null;

            if (this.ID == Guid.Empty)
            {
                template = new Entities.Template();
                template.CreatedBy = this.CreatedBy;
                template.CreatedDate = DateTime.Now;
            }
            else
            {
                template = pSession.Get<Entities.Template>(this.ID);
            }

            if (this.Name != template.Name)
                template.Name = this.Name;

            if (this.Description != template.Description)
                template.Description = this.Description;
                        
            template.IsDeleted = this.IsDeleted;
            template.IsDisabled = this.IsDisabled;

            template.UpdatedBy = this.UpdatedBy;
            template.UpdatedDate = DateTime.Now;

            //if (this.MachineItems != null && this.MachineItems.Count > 0)
            //{
            //    if (template.MachineItems != null && template.MachineItems.Count > 0)
            //    {
            //        while (template.MachineItems.Count > 0)
            //        {
            //            template.MachineItems.RemoveAt(0);
            //        }
            //    }

            //    foreach (var item in this.MachineItems)
            //    {
            //        template.MachineItems.Add(item.ToBusinessObject(pSession));
            //    }
            //}
           
            return template;
        }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TemplateMachinery
    {
        public TemplateMachinery()
        {
            this.ID = Guid.Empty;
            this.MachineItemID = null;
        }

        public TemplateMachinery(Entities.TemplateMachinery pBusinessObject)
        {
            this.ID = pBusinessObject.ID;
            this.MachineItem = new MachineType(pBusinessObject.MachineItem);
            this.MachineItemID = pBusinessObject.MachineItem.ID;
            this.ParentID = pBusinessObject.ParentId;
            this.CurrentType = this.MachineItem.Category;
            switch (this.CurrentType)
            {
                case "SYSTEM":
                    {
                        this.ParentType = "UNKNOWN";
                        this.ChildType = "SUBSYSTEM";
                        break;
                    }
                case "SUBSYSTEM":
                    {
                        this.ParentType = "SYSTEM";
                        this.ChildType = "EQUIPMENT";
                        break;
                    }
                case "EQUIPMENT":
                    {
                        this.ParentType = "SUBSYSTEM";
                        this.ChildType = "COMPONENT";
                        break;
                    }
                case "COMPONENT":
                    {
                        this.ParentType = "EQUIPMENT";
                        this.ChildType = "SUBCOMPONET";
                        break;
                    }
                case "SUBCOMPONET":
                    {
                        this.ParentType = "COMPONENT";
                        this.ChildType = "UNKNOWN";
                        break;
                    }
            }
        }

        [DataMember]
        public Guid ID
        { get; private set; }

        [DataMember]
        public MachineType MachineItem
        { get; private set; }

        [DataMember]
        public Guid? MachineItemID
        { get; private set; }

        [DataMember]
        public Guid? ParentID
        { get; set; }

        [DataMember]
        public string CurrentType
        { get; private set; }

        [DataMember]
        public string ParentType
        { get; private set; }

        [DataMember]
        public string ChildType
        { get; private set; }

        [DataMember]
        public bool AttachedToVessel
        { get; set; }

        [DataMember]
        public Guid VesselItemID
        { get; set; }

        internal Entities.TemplateMachinery ToBusinessObject(NHibernate.ISession pSession)
        {
            Entities.TemplateMachinery tMachine = null;

            if (this.ID == Guid.Empty)
            {
                tMachine = new Entities.TemplateMachinery();
            }
            else
            {
                tMachine = pSession.Get<Entities.TemplateMachinery>(this.ID);
            }

            Activities.AdminActivities adminActivities = new Activities.AdminActivities(pSession);
            tMachine.MachineItem = adminActivities.GetItemByID(this.MachineItemID.Value);
            tMachine.ParentId = this.ParentID;            

            //if (this.ConstituentIDs.Count > 0)
            //{
            //    foreach (var id in this.ConstituentIDs)
            //    {
            //        tMachine.Constituents = this.ConstituentIDs.ToBusinessObject(pSession);
            //    }
            //}

            return tMachine;
        }
    }

    public class WebPage
    {
        public WebPage()
        {
            this.ID = Guid.Empty;
        }

        public WebPage(Entities.WebPage pBusinessObject)
        {
            this.ID = pBusinessObject.ID;
            this.Title = pBusinessObject.Title;
            this.Description = pBusinessObject.Description;
            this.RelativeUrl = pBusinessObject.RelativeUrl;
            this.SequneceNo = pBusinessObject.SequneceNo;
            this.ParentID = pBusinessObject.ParentID;
            this.PermissionSet = pBusinessObject.PermissionSet;
            this.Type = pBusinessObject.Type;
            this.Zone = pBusinessObject.Zone;
            this.PageCode = pBusinessObject.PageCode;
            this.IsEnabled = pBusinessObject.IsEnabled;
        }

        public Guid ID
        { get; set; }

        public string Title
        { get; set; }

        public string Description
        { get; set; }

        public string RelativeUrl
        { get; set; }

        public string PermissionSet
        { get; set; }

        public string Type
        { get; set; }

        public int SequneceNo
        { get; set; }

        public Guid? ParentID
        { get; set; }

        public string Zone
        { get; set; }

        public string PageCode
        { get; set; }

        public bool IsEnabled
        { get; set; }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Vessel
    {
        public Vessel()
        {
            this.ID = Guid.Empty;
        }

        public Vessel(Entities.Vessel pBusinessObject)
        {
            this.ID = pBusinessObject.ID;
            this.Name = pBusinessObject.Name;
            this.ImoNumber = pBusinessObject.ImoNumber;
            this.CallSign = pBusinessObject.CallSign;
            this.HullNo = pBusinessObject.HullNo;
            this.PortOfRegistry = pBusinessObject.PortOfRegistry;
            this.Flag = pBusinessObject.Flag;
            this.InmarsatPhoneNo = pBusinessObject.InmarsatPhoneNo;
            this.Fax = pBusinessObject.Fax;
            this.EMail = pBusinessObject.EMail;
            this.ClassificationSociety = pBusinessObject.ClassificationSociety;
            this.IsDisabled = pBusinessObject.IsDisabled;
            this.IsDeleted = pBusinessObject.IsDeleted;
            this.CreatedBy = pBusinessObject.CreatedBy;
            this.CreatedDate = pBusinessObject.CreatedDate;
            this.UpdatedBy = pBusinessObject.UpdatedBy;
            this.UpdatedDate = pBusinessObject.UpdatedDate;
            this.IsReleased = pBusinessObject.IsReleased;
            this.ReleasedDate = pBusinessObject.ReleasedDate;
            this.ReleasedBy = pBusinessObject.ReleasedBy;
            this.RecordNum = pBusinessObject.RecordNum;

            if (pBusinessObject.SystemsTemplate != null)
                this.TemplateID = pBusinessObject.SystemsTemplate.ID;
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public int RecordNum
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string ImoNumber
        { get; set; }

        [DataMember]
        public string CallSign
        { get; set; }

        [DataMember]
        public string HullNo
        { get; set; }

        [DataMember]
        public string PortOfRegistry
        { get; set; }

        [DataMember]
        public string Flag
        { get; set; }

        [DataMember]
        public string InmarsatPhoneNo
        { get; set; }

        [DataMember]
        public string Fax
        { get; set; }

        [DataMember]
        public string EMail
        { get; set; }

        [DataMember]
        public string ClassificationSociety
        { get; set; }

        [DataMember]
        public Guid? TemplateID
        { get; set; }

        [DataMember]
        public bool IsReleased
        { get; set; }

        [DataMember]
        public DateTime? ReleasedDate
        { get; set; }

        [DataMember]
        public Guid ReleasedBy
        { get; set; }

        [DataMember]
        public bool IsDisabled
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        [DataMember]
        public Guid CreatedBy
        { get; set; }

        [DataMember]
        public DateTime CreatedDate
        { get; set; }

        [DataMember]
        public Guid UpdatedBy
        { get; set; }

        [DataMember]
        public DateTime UpdatedDate
        { get; set; }
      
        internal Entities.Vessel ToBusinessObject(ISession pSession)
        {
            Entities.Vessel bizObject = null;
            Activities.AdminActivities adminActivities = new Activities.AdminActivities(pSession);

            if (this.ID != Guid.Empty)
            {
                bizObject = adminActivities.GetVesselByCode(this.ID);                
            }
            else
            {
                bizObject = new Entities.Vessel();
            }

            bizObject.Name = this.Name;
            bizObject.ImoNumber = this.ImoNumber;
            bizObject.CallSign = this.CallSign;
            bizObject.HullNo = this.HullNo;
            bizObject.PortOfRegistry = this.PortOfRegistry;
            bizObject.Flag = this.Flag;
            bizObject.InmarsatPhoneNo = this.InmarsatPhoneNo;
            bizObject.Fax = this.Fax;
            bizObject.EMail = this.EMail;
            bizObject.ClassificationSociety = this.ClassificationSociety;
            bizObject.IsDisabled = this.IsDisabled;
            bizObject.IsDeleted = this.IsDeleted;
            bizObject.CreatedBy = this.CreatedBy;
            bizObject.CreatedDate = this.CreatedDate;
            bizObject.UpdatedBy = this.UpdatedBy;
            bizObject.UpdatedDate = this.UpdatedDate;
            bizObject.IsReleased = this.IsReleased;
            bizObject.ReleasedDate = this.ReleasedDate;
            bizObject.ReleasedBy = this.ReleasedBy;
            bizObject.RecordNum = this.RecordNum;


            if (this.TemplateID != null)
            {
                bizObject.SystemsTemplate = adminActivities.GetTemplateByID(this.TemplateID.Value);
            }

            return bizObject;
        }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SystemCode
    {
        public SystemCode()
        {
            this.ID = Guid.Empty;
            this.CodeValues = new List<SystemCodeData>();
        }

        public SystemCode(Entities.SystemCode pBusinessObject)
        {
            this.ID = pBusinessObject.ID;
            this.Name = pBusinessObject.Name;
            this.CodeValues = new List<SystemCodeData>();
            this.IsDeleted = pBusinessObject.IsDeleted;

            if (pBusinessObject.CodeValues != null)
            {
                foreach (var item in pBusinessObject.CodeValues)
                {
                    this.CodeValues.Add(new SystemCodeData(item));
                }
            }
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public IList<SystemCodeData> CodeValues
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }        
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SystemCodeData
    {
        public SystemCodeData()
        {
            this.ID = Guid.Empty;
            this.ParentID = Guid.Empty;
        }

        public SystemCodeData(Entities.SystemCodeData pBusinessObject)
        {
            // TODO: Complete member initialization
            this.ID = pBusinessObject.ID;
            this.Name = pBusinessObject.Name;
            this.ParentID = pBusinessObject.ParentID;
            this.Value = pBusinessObject.Value;
            this.IsDeleted = pBusinessObject.IsDeleted;
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string Value
        { get; set; }

        [DataMember]
        public Guid ParentID
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }       
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class VesselMachine
    {
        public VesselMachine()
        {
            this.ID = Guid.Empty;
            this.Parent = Guid.Empty;
        }

        public VesselMachine(Business.Entities.VesselMachine pBusinessObject)
        {
            this.ID = pBusinessObject.ID;
            this.Name = pBusinessObject.Product.Name;
            this.Specifications = pBusinessObject.Specifications;
            this.VesselItemType = pBusinessObject.Type.Category.ToString();
            this.Parent = (pBusinessObject.Parent != null ? pBusinessObject.Parent.ID : Guid.Empty);
            this.IsBusinessCritical = pBusinessObject.Type.IsBusinessCritical;
            this.IsSafetyCritical = pBusinessObject.Type.IsSafetyCritical;
            this.IsEnvironmentCritical = pBusinessObject.Type.IsEnvironmentCritical;
            this.IsMandatory = pBusinessObject.Type.IsMandatory;
            this.IsDeleted = pBusinessObject.IsDeleted;
            this.IsDisabled = pBusinessObject.IsDisabled;
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Name
        { get; set; }

        [DataMember]
        public string Description
        { get; set; }

        [DataMember]
        public string Specifications
        { get; set; }

        [DataMember]
        public string VesselItemType
        { get; set; }

        [DataMember]
        public Guid Parent
        { get; set; }

        [DataMember]
        public bool IsBusinessCritical
        { get; set; }

        [DataMember]
        public bool IsSafetyCritical
        { get; set; }

        [DataMember]
        public bool IsEnvironmentCritical
        { get; set; }

        [DataMember]
        public bool IsMandatory
        { get; set; }

        [DataMember]
        public bool IsDisabled
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        public Business.Entities.VesselMachine ToBusinessObject(ISession pSession)
        {
            Entities.VesselMachine bizObject = null;
            Activities.AdminActivities adminActivities = new Activities.AdminActivities(pSession);

            if (this.ID != Guid.Empty)
            {
                bizObject = adminActivities.GetVesselItemByCode(this.ID);
            }
            else
            {
                bizObject = new Entities.VesselMachine();
            }
                        
            bizObject.Specifications = this.Specifications;            
            bizObject.IsDeleted = this.IsDeleted;
            bizObject.IsDisabled = this.IsDisabled;

            if (this.Parent != Guid.Empty)
            {
                bizObject.Parent = adminActivities.GetVesselItemByCode(this.Parent);
            }

            return bizObject;
        }
    }

    [DataContract(Namespace = "Landscape")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Job
    {
        public Job()
        { this.ID = Guid.Empty; }

        public Job(Business.Entities.Job pBusinessObject)
        {
            this.ID = pBusinessObject.ID;
            this.Code = pBusinessObject.Code;
            this.Title = pBusinessObject.Title;
            this.Description = (pBusinessObject.Description == null ? string.Empty : pBusinessObject.Description);
            this.Periodicity = pBusinessObject.Periodicity;
            //this.PeriodicityUnit = pBusinessObject.PeriodicityUnit;
            this.Priority = pBusinessObject.Priority;
            this.JobType = pBusinessObject.Type.ToString();
            this.JobVersion = pBusinessObject.JobVersion;
            //this.Measurements = pBusinessObject.Measurements;
            this.WorkordersCount = pBusinessObject.Workorders.Count;
            this.IsDeleted = pBusinessObject.IsDeleted;
            this.HistoryCount = pBusinessObject.History.Count;
            this.ChangeRequestsCount = pBusinessObject.ChangeRequests.Count;
            this.AttachmentsCount = pBusinessObject.Attachments.Count;
            this.IsReleased = pBusinessObject.IsReleased;
            this.ReleasedDate = pBusinessObject.ReleasedDate;
            this.ReleasedBy = pBusinessObject.ReleasedBy;
            this.CreatedBy = pBusinessObject.CreatedBy;
            this.CreatedDate = pBusinessObject.CreatedDate;
            this.UpdatedBy = pBusinessObject.UpdatedBy;
            this.UpdatedDate = pBusinessObject.UpdatedDate;
            this.Periodicity2 = pBusinessObject.Periodicity + " " + pBusinessObject.PeriodicityUnit;
            this.UpdatedDate2 = pBusinessObject.UpdatedDate.ToString("dd-MMM-yyyy");
            this.ReleasedDate2 = (ReleasedDate.HasValue ? pBusinessObject.ReleasedDate.Value.ToString("dd-MMM-yyyy") : string.Empty);

            AdministrativeActions adminActs = new AdministrativeActions();
            var user = adminActs.GetUserByID(pBusinessObject.UpdatedBy);
            this.UpdatedBy2 = user.FirstName + " " + user.LastName;

            if (this.IsReleased)
            {
                user = adminActs.GetUserByID(pBusinessObject.ReleasedBy);
                this.ReleasedBy2 = user.FirstName + " " + user.LastName;
            }
        }

        [DataMember]
        public Guid ID
        { get; set; }

        [DataMember]
        public string Code
        { get; set; }

        [DataMember]
        public string Title
        { get; set; }

        [DataMember]
        public string Description
        { get; set; }

        [DataMember]
        public int Periodicity
        { get; set; }

        /// <summary>
        /// Units for the periodicity
        /// 1. Running Hours
        /// 2. Days
        /// 3. Months
        /// </summary>
        [DataMember]
        public string PeriodicityUnit
        { get; set; }

        /// <summary>
        /// Priority of the job. Possible values
        /// 1. Normal
        /// 2. Moderate
        /// 3. Urgent
        /// </summary>
        [DataMember]
        public string Priority
        { get; set; }

        [DataMember]
        public string JobType
        { get; set; }

        [DataMember]
        public int JobVersion
        { get; set; }

        [DataMember]
        public IList<string> Measurements
        { get; set; }

        [DataMember]
        public int WorkordersCount
        { get; set; }

        [DataMember]
        public int HistoryCount
        { get; set; }

        [DataMember]
        public int ChangeRequestsCount
        { get; set; }

        [DataMember]
        public int AttachmentsCount
        { get; set; }

        [DataMember]
        public bool IsDeleted
        { get; set; }

        [DataMember]
        public bool IsReleased
        { get; set; }

        [DataMember]
        public DateTime? ReleasedDate
        { get; set; }

        [DataMember]
        public Guid ReleasedBy
        { get; set; }

        [DataMember]
        public Guid CreatedBy
        { get; set; }

        [DataMember]
        public DateTime CreatedDate
        { get; set; }

        [DataMember]
        public Guid UpdatedBy
        { get; set; }

        [DataMember]
        public DateTime UpdatedDate
        { get; set; }

        [DataMember]
        public Guid VesselItemID
        { get; set; }

        [DataMember]
        public string Periodicity2
        { get; set; }

        [DataMember]
        public string UpdatedDate2
        { get; set; }

        [DataMember]
        public string UpdatedBy2
        { get; set; }

        [DataMember]
        public string ReleasedDate2
        { get; set; }

        [DataMember]
        public string ReleasedBy2
        { get; set; }

        public Business.Entities.Job ToBusinessObject(ISession pSession)
        {
            Entities.Job bizObject = null;
            Activities.AdminActivities adminActivities = new Activities.AdminActivities(pSession);

            if (this.ID != Guid.Empty)
            {
                bizObject = adminActivities.GetJobByCode(this.ID);
            }
            else
            {
                bizObject = new Entities.Job();
            }

            bizObject.Code = this.Code;
            bizObject.Title = this.Title;
            bizObject.Description = this.Description;
            bizObject.Periodicity = this.Periodicity;
            //bizObject.PeriodicityUnit =  this.PeriodicityUnit;
            bizObject.Priority = this.Priority;
            bizObject.Type =  (Business.JobType)Enum.Parse(typeof(Business.JobType),  this.JobType);
            bizObject.JobVersion = this.JobVersion;
            bizObject.Measurements = this.Measurements;
            bizObject.IsDeleted = this.IsDeleted;
            bizObject.IsReleased = this.IsReleased;
            bizObject.ReleasedDate = this.ReleasedDate;
            bizObject.ReleasedBy = this.ReleasedBy;
            bizObject.CreatedBy = this.CreatedBy;
            bizObject.CreatedDate = this.CreatedDate;
            bizObject.UpdatedBy = this.UpdatedBy;
            bizObject.UpdatedDate = this.UpdatedDate;

            return bizObject;
        }
    }
}
